package financeiro.web.filter;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;

import org.hibernate.SessionFactory;

import financeiro.util.HibernateUtil;

public class ConexaoHibernateFilter implements Filter{

	private SessionFactory sf;
	
	public SessionFactory getSf() {
		return sf;
	}

	public void setSf(SessionFactory sf) {
		this.sf = sf;
	}

	@Override
	public void destroy() {	}

	@Override
	public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse,
			FilterChain chain) throws ServletException {
		try {
			getSf().getCurrentSession().beginTransaction();
			chain.doFilter(servletRequest, servletResponse);
			getSf().getCurrentSession().getTransaction().commit();
			getSf().getCurrentSession().close();
		} catch (Throwable ex) {
			try {
				if(getSf().getCurrentSession().getTransaction().isActive()){
					getSf().getCurrentSession().beginTransaction().rollback();
				}
			} catch (Throwable t) {
				System.out.println(t.getMessage());
			}
			throw new ServletException(ex);
		}		
	}

	@Override
	public void init(FilterConfig config) throws ServletException {
		setSf(HibernateUtil.getSessionFactory());		
	}
}
